import axios from "axios";
import type { InternalAxiosRequestConfig } from "axios";
import { Toast } from "antd-mobile";

type AxiosConfig = InternalAxiosRequestConfig<any>;

declare module "axios" {
  interface AxiosInstance {
    postFromData: (url: string, config: Partial<AxiosConfig>) => Promise<any>;
  }
}

const errosMap: any = {
  9999: "登录状态失效，请重新登录",
  9001: "服务端错误",
  8001: "用户业务错误",
  8002: "医生业务错误",
  8003: "公共业务错误"
  //  0000:	'请求接口成功'
};

//创建axios 的实例
const service = axios.create({
  baseURL: "/",
  timeout: 1000000,
});

//拦截请求
//拦截请求
service.interceptors.request.use(
  (config) => {
    Toast.show({
      content: "loading...",
      duration: 0,
    });
 //例如获取token
    const token = localStorage.getItem("token");

    const sessionId = localStorage.getItem("sessionId");
    const doctorId = localStorage.getItem("doctorId");

    if (!!token) {
      config.headers["Authorization"] = "Bearer " + token;
    }

    if (sessionId && doctorId) {
      config.headers["Sessionid"] = sessionId;
      config.headers["Doctorid"] = doctorId;
    }

    return config;
  },
  (error) => {
    // console.log(error);
  }
);


//拦截响应
service.interceptors.response.use(
  (response) => {
    Toast.clear();
    const data = response.data;
    if (data) {
      if (data.status !== "0000") {
        // Toast.show({
        //   icon: "error",
        //   content: errosMap[data.status],
        // });
      }
    }

    return data;
    //处理正确响应结果
  },
  (error) => {
    //
    // console.log(error);
    // Toast.show({
    //   icon: "error",
    //   content: error.message,
    // });
  }
);

//处理 formData;

service.postFromData = (url, config) => {
  const { data = {} } = config;
  const formData = new FormData();
  if (data && typeof data === "object") {
    for (const key in data) {
      formData.append(key, data[key]);
    }
  }
  return service.post(url, formData, {
    ...config,
    headers: {
      // ...config.headers,
      "Content-Type": "application/json",
    },
  });
};

export default service;
